package helpers;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.TreeMap;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.gson.Gson;

public class ConnectionHelper {
	
	public static String getContent(String url) {
		return callGetContent(url, null, Method.GET);
	}
	
	public static String getContent(String url, Map<String, String> params) {
		return callGetContent(url, params, Method.GET);
	}
	
	public static String postContent(String url) {
		return callGetContent(url, null, Method.POST);
	}
	
	public static String postContent(String url, Map<String, String> params) {
		return callGetContent(url, params, Method.POST);
	}
	
	private static String callGetContent(String url, Map<String, String> params, Connection.Method method) {
		String content = "";
		
		try {
			Connection conn = Jsoup.connect(url)
								.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
								.header("accept-Language", "en-us,en;q=0.5")
								.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
								.followRedirects(true)
								.ignoreContentType(true)
								.method(method)
								.timeout(3000);
			if (params != null && params.size() > 0) {
				conn = conn.data(params);
			}
			
			
			content = conn.execute().body();
		} catch (Exception e) {
			Map<String, Object> result = new TreeMap<String, Object>();
			
			result.put("status", "error");
			result.put("message", e.toString());
			
			content = new Gson().toJson(result);
		}
		
		return content;
	}
	
	public static void runUrl(String url) {
		callRunContent(url, null, HTTPMethod.GET);
	}
	
	public static void runUrl(String url, Map<String, String> params) {
		callRunContent(url, params, HTTPMethod.GET);
	}
	
	public static void runUrlPost(String url) {
		callRunContent(url, null, HTTPMethod.POST);
	}
	
	public static void runUrlPost(String url, Map<String, String> params) {
		callRunContent(url, params, HTTPMethod.POST);
	}
	
	private static void callRunContent(String theUrl, Map<String, String> params, HTTPMethod method) {
		URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
		try {
			URL url = new URL(theUrl);
			try {
				HTTPRequest request1 = new HTTPRequest(url, method);
				
	            request1.setHeader(new HTTPHeader("Content-Type", "application/x-www-form-urlencoded"));
	            
	            if (params != null && params.size() > 0) {
		            String strParams = "";
		            for (Map.Entry<String, String> entry : params.entrySet()) {
		            	if (!strParams.isEmpty()) strParams += "&";
						strParams += entry.getKey() + "=" + entry.getValue();
					}
		            request1.setPayload(strParams.getBytes());
	            }
	            
	            fetcher.fetchAsync(request1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
//	public static String getContentUrl(String theUrl) {
//		StringBuilder content = new StringBuilder();
//
//	    // many of these calls can throw exceptions, so i've just
//	    // wrapped them all in one try/catch statement.
//	    try
//	    {
//	    	// create a url object
//	    	URL url = new URL(theUrl);
//
//	    	// create a urlconnection object
//	    	URLConnection urlConnection = url.openConnection();
//
//	    	// wrap the urlconnection in a bufferedreader
//	    	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//
//	    	String line;
//
//	    	// read from the urlconnection via the bufferedreader
//	    	while ((line = bufferedReader.readLine()) != null)
//	    	{
//	    		content.append(line + "\n");
//	    	}
//	    	bufferedReader.close();
//	    }
//	    catch(Exception e)
//	    {
//	    }
//	    return content.toString();
//	}
}